import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Card, Row, Col, Select, List, Rate, Typography, message, Tabs, Input, Button, Modal, Form, Table, Space, Empty } from 'antd';

const { Title, Text } = Typography;
const { Option } = Select;
const { TabPane } = Tabs;
const { Search } = Input;

const timeSlots = [
  { time: '1-2节 8:30-10:10', slot: 1, section: '1-2节', timeRange: '8:30-10:10' },
  { time: '3-4节 10:30-12:10', slot: 3, section: '3-4节', timeRange: '10:30-12:10' },
  { time: '5-6节 14:00-15:40', slot: 5, section: '5-6节', timeRange: '14:00-15:40' },
  { time: '7-8节 16:00-17:40', slot: 7, section: '7-8节', timeRange: '16:00-17:40' },
  { time: '9-10节 19:00-20:40', slot: 9, section: '9-10节', timeRange: '19:00-20:40' }
];

const weekDays = ['周一', '周二', '周三', '周四', '周五'];

const Home = () => {
  const [majors, setMajors] = useState([]);
  const [grades, setGrades] = useState([]);
  const [selectedMajor, setSelectedMajor] = useState(null);
  const [selectedGrade, setSelectedGrade] = useState(null);
  const [allCourses, setAllCourses] = useState([]);
  const [filteredCourses, setFilteredCourses] = useState([]);
  const [teachers, setTeachers] = useState([]);
  const [loading, setLoading] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [ratingModalVisible, setRatingModalVisible] = useState(false);
  const [selectedCourse, setSelectedCourse] = useState(null);
  const [courseDetailVisible, setCourseDetailVisible] = useState(false);
  const [filters, setFilters] = useState({
    waterLevel: null,    // 水课程度
    scoreLevel: null,    // 得分高低
    teacherName: '',     // 教师名称
    courseName: ''       // 课程名称
  });
  const [schedule, setSchedule] = useState(
    timeSlots.map(({ time, slot, section, timeRange }) => ({
      time,
      slot,
      section,
      timeRange,
      周一: null,
      周二: null,
      周三: null,
      周四: null,
      周五: null
    }))
  );
  const [form] = Form.useForm();

  // 获取专业列表
  useEffect(() => {
    axios.get('http://localhost:5000/api/majors/')
      .then(response => {
        console.log('专业列表响应:', response.data);
        if (response.data && response.data.data) {
          setMajors(response.data.data);
        } else {
          console.error('专业列表数据格式错误:', response.data);
          message.error('专业列表数据格式错误');
        }
      })
      .catch(error => {
        console.error('获取专业列表失败:', error.response || error);
        message.error(`获取专业列表失败: ${error.response?.data?.message || error.message}`);
      });
  }, []);

  // 获取年级列表
  useEffect(() => {
    axios.get('http://localhost:5000/api/courses/grades')
      .then(response => {
        console.log('年级列表响应:', response.data);
        if (response.data && response.data.data) {
          setGrades(response.data.data);
        } else {
          console.error('年级列表数据格式错误:', response.data);
          message.error('年级列表数据格式错误');
        }
      })
      .catch(error => {
        console.error('获取年级列表失败:', error.response || error);
        message.error(`获取年级列表失败: ${error.response?.data?.message || error.message}`);
      });
  }, []);

  // 获取教师列表
  useEffect(() => {
    axios.get('http://localhost:5000/api/courses/teachers')
      .then(response => {
        if (response.data && response.data.data) {
          setTeachers(response.data.data);
        }
      })
      .catch(error => console.error('获取教师列表失败:', error));
  }, []);

  // 当选择专业和年级时获取课程
  useEffect(() => {
    if (selectedMajor && selectedGrade) {
      setLoading(true);
      axios.get(`http://localhost:5000/api/major-plans/majors/${selectedMajor}/grade/${selectedGrade}`)
        .then(response => {
          if (response.data && response.data.data) {
            setAllCourses(response.data.data);
            setFilteredCourses(response.data.data);
          }
        })
        .catch(error => {
          console.error('获取课程列表失败:', error);
          message.error('获取课程列表失败');
        })
        .finally(() => setLoading(false));
    }
  }, [selectedMajor, selectedGrade]);

  // 处理筛选条件变化
  const handleFilterChange = (type, value) => {
    setFilters(prev => ({ ...prev, [type]: value }));
  };

  // 应用筛选条件
  const applyFilters = () => {
    let filtered = [...allCourses];

    // 水课程度筛选
    if (filters.waterLevel) {
      const [min, max] = filters.waterLevel.split('-').map(Number);
      filtered = filtered.filter(course => {
        const score = course.水课程度;
        return score >= min && score <= max;
      });
    }

    // 得分高低筛选
    if (filters.scoreLevel) {
      const [min, max] = filters.scoreLevel.split('-').map(Number);
      filtered = filtered.filter(course => {
        const score = course.得分高低;
        return score >= min && score <= max;
      });
    }

    // 教师名称筛选
    if (filters.teacherName) {
      const keywords = filters.teacherName.trim().split(/\s+/); // 将输入按空格分割成关键词数组
      filtered = filtered.filter(course => 
        course.教师姓名 && keywords.every(keyword => 
          course.教师姓名.includes(keyword)
        )
      );
    }

    // 课程名称或编号筛选
    if (filters.courseName) {
      const searchText = filters.courseName.toLowerCase();
      filtered = filtered.filter(course =>
        (course.课程名称 && course.课程名称.toLowerCase().includes(searchText)) ||
        (course.课程编号 && course.课程编号.toLowerCase().includes(searchText))
      );
    }

    setFilteredCourses(filtered);
  };

  // 添加课程到课表
  const addToSchedule = (course, timeSlot, day) => {
    console.log('添加课程:', course);
    console.log('时间段:', timeSlot);
    console.log('星期:', day);
    
    setSchedule(prev => {
      const newSchedule = [...prev];
      const timeIndex = newSchedule.findIndex(t => t.time === timeSlot.time);
      
      if (timeIndex !== -1) {
        newSchedule[timeIndex] = {
          ...newSchedule[timeIndex],
          [day]: {
            课程名称: course.课程名称,
            教师姓名: course.教师姓名,
            教室: course.教室 || '未安排'
          }
        };
      }
      return newSchedule;
    });
    message.success(`已将 ${course.课程名称} 添加到课表`);
  };

  // 从课表中移除课程
  const removeFromSchedule = (timeSlot, day) => {
    setSchedule(prev => {
      const newSchedule = [...prev];
      const timeIndex = newSchedule.findIndex(t => t.time === timeSlot.time);
      
      if (timeIndex !== -1) {
        newSchedule[timeIndex] = {
          ...newSchedule[timeIndex],
          [day]: null
        };
      }
      return newSchedule;
    });
    message.success('课程已从课表中移除');
  };

  const waterLevelOptions = [
    { label: '1-2分(非常不水)', value: '1-2' },
    { label: '3-4分(较不水)', value: '3-4' },
    { label: '5-6分(一般)', value: '5-6' },
    { label: '7-8分(较水)', value: '7-8' },
    { label: '9-10分(非常水)', value: '9-10' }
  ];

  const scoreLevelOptions = [
    { label: '1-2分(很难得分)', value: '1-2' },
    { label: '3-4分(较难得分)', value: '3-4' },
    { label: '5-6分(一般)', value: '5-6' },
    { label: '7-8分(较易得分)', value: '7-8' },
    { label: '9-10分(很易得分)', value: '9-10' }
  ];

  const teacherOptions = teachers.map(teacher => ({
    label: teacher.教师姓名,
    value: teacher.教师编号,
  }));

  const gradeOptions = grades.map(grade => ({
    label: `${grade}年级`,
    value: grade,
  }));

  // 渲染课表
  const renderSchedule = () => {
    const columns = [
      {
        title: '时间',
        dataIndex: 'time',
        key: 'time',
        width: 160,
        render: (_, record) => (
          <div style={{ padding: '8px', textAlign: 'center' }}>
            <div>{record.time}</div>
          </div>
        )
      },
      ...weekDays.map(day => ({
        title: day,
        dataIndex: day,
        key: day,
        width: 'calc((100% - 160px) / 5)',
        render: (courseData, record) => (
          <div style={{ 
            minHeight: '80px', 
            padding: '8px', 
            border: '1px solid #f0f0f0',
            background: courseData ? '#f0f8ff' : '#fff'
          }}>
            {courseData ? (
              <>
                <div style={{ fontSize: '14px', fontWeight: 'bold', marginBottom: '4px' }}>
                  {courseData.课程名称}
                </div>
                <div style={{ fontSize: '12px', color: '#666', marginBottom: '2px' }}>
                  {courseData.教师姓名}
                </div>
                {courseData.教室 && (
                  <div style={{ fontSize: '12px', color: '#888', marginBottom: '4px' }}>
                    {courseData.教室}
                  </div>
                )}
                <Button 
                  type="link" 
                  danger 
                  size="small"
                  style={{ padding: 0 }}
                  onClick={() => removeFromSchedule(record, day)}
                >
                  删除
                </Button>
              </>
            ) : (
              <Button 
                type="dashed" 
                style={{ 
                  width: '100%',
                  height: '100%',
                  border: '1px dashed #d9d9d9'
                }}
                onClick={() => {
                  if (selectedCourse) {
                    addToSchedule(selectedCourse, record, day);
                  } else {
                    message.info('请先选择一门课程');
                  }
                }}
              >
                点击添加课程
              </Button>
            )}
          </div>
        )
      }))
    ];

    return (
        <Table 
        dataSource={schedule} 
          columns={columns} 
          pagination={false}
          bordered
          rowKey="time"
          style={{
            width: '100%',
          maxWidth: '1200px',
            margin: '0 auto'
          }}
        />
    );
  };

  // 如果未选择专业和年级，显示选择界面
  if (!selectedMajor || !selectedGrade) {
    return (
      <div style={{ padding: '24px' }}>
        <Title level={2}>课程选择系统</Title>
        <Card>
          <Space direction="vertical" style={{ width: '100%', textAlign: 'center' }}>
            <Title level={4}>请选择专业和年级</Title>
            <Select
              style={{ width: 300 }}
              placeholder="选择专业"
              onChange={setSelectedMajor}
            >
              {majors.map(major => (
                <Option key={major.专业编号} value={major.专业编号}>
                  {major.专业名称}
                </Option>
              ))}
            </Select>
            <Select
              style={{ width: 300 }}
              placeholder="选择年级"
              onChange={setSelectedGrade}
              disabled={!selectedMajor}
            >
              {gradeOptions.map(option => (
                <Option key={option.value} value={option.value}>
                  {option.label}
                </Option>
              ))}
            </Select>
          </Space>
        </Card>
      </div>
    );
  }

  return (
    <div style={{ padding: '24px' }}>
      <Title level={2}>课程选择系统</Title>
      
      <Row gutter={[16, 16]}>
        <Col span={24}>
          <Card title="当前选择">
            <Space>
              <Text>专业：{majors.find(m => m.专业编号 === selectedMajor)?.专业名称}</Text>
              <Text>年级：{selectedGrade}年级</Text>
              <Button onClick={() => {
                setSelectedMajor(null);
                setSelectedGrade(null);
              }}>
                重新选择
              </Button>
            </Space>
          </Card>
        </Col>

        <Col span={24}>
          <Card title="筛选条件">
            <Space direction="vertical" style={{ width: '100%' }}>
              <Select
                style={{ width: '100%' }}
                placeholder="选择水课程度"
                onChange={value => handleFilterChange('waterLevel', value)}
                options={waterLevelOptions}
                allowClear
              />
              <Select
                style={{ width: '100%' }}
                placeholder="选择得分高低"
                onChange={value => handleFilterChange('scoreLevel', value)}
                options={scoreLevelOptions}
                allowClear
              />
              <Search
                placeholder="搜索教师名称"
                onSearch={value => handleFilterChange('teacherName', value)}
                style={{ width: '100%' }}
                allowClear
              />
              <Search
                placeholder="搜索课程名称或编号"
                onSearch={value => handleFilterChange('courseName', value)}
                style={{ width: '100%' }}
                allowClear
              />
              <Button 
                type="primary" 
                onClick={applyFilters}
                style={{ width: '100%' }}
              >
                应用筛选
              </Button>
            </Space>
          </Card>
        </Col>

        <Col span={12}>
          <Card title="课程列表" loading={loading}>
            <List
              itemLayout="vertical"
              dataSource={filteredCourses}
              pagination={{
                pageSize: 5,
                total: filteredCourses.length,
              }}
              renderItem={course => (
                <List.Item
                  actions={[
                    <Button 
                      type="primary"
                      onClick={() => {
                        setSelectedCourse(course);
                        message.success(`已选中${course.教师姓名}老师的${course.课程名称}，请在课表中选择要添加的时间段`);
                      }}
                    >
                      选择此课程
                    </Button>,
                    <Button 
                      onClick={() => {
                        setSelectedCourse(course);
                        setCourseDetailVisible(true);
                      }}
                    >
                      查看详情
                    </Button>
                  ]}
                >
                  <List.Item.Meta
                    title={course.课程名称}
                    description={
                      <Space direction="vertical">
                        <Text>课程编号：{course.原始课程编号}</Text>
                        <Text>学分：{course.学分}</Text>
                        <Text>教师：{course.教师姓名}</Text>
                        <Text>教室：{course.教室 || '未安排'}</Text>
                        <Space direction="vertical">
                          <Text>水课程度：{course.水课程度?.toFixed(1) || 'N/A'} / 10</Text>
                          <Text>得分高低：{course.得分高低?.toFixed(1) || 'N/A'} / 10</Text>
                          <Text>评价数量：{course.评价数量}</Text>
                        </Space>
                      </Space>
                    }
                  />
                </List.Item>
              )}
            />
          </Card>
        </Col>

        <Col span={12}>
          <Card title="课表编排">
            {renderSchedule()}
          </Card>
        </Col>
      </Row>

      <Modal
        title="课程详情"
        visible={courseDetailVisible}
        onCancel={() => setCourseDetailVisible(false)}
        footer={[
          <Button key="close" onClick={() => setCourseDetailVisible(false)}>
            关闭
          </Button>,
          <Button
            key="rate"
            type="primary"
            onClick={() => {
              setCourseDetailVisible(false);
              setRatingModalVisible(true);
            }}
          >
            评价课程
          </Button>
        ]}
        width={600}
      >
        {selectedCourse && (
          <Space direction="vertical" style={{ width: '100%' }}>
            <Title level={4}>{selectedCourse.课程名称}</Title>
            <Text>课程编号：{selectedCourse.原始课程编号}</Text>
            <Text>学分：{selectedCourse.学分}</Text>
            <Title level={5}>教师信息</Title>
            <Text>教师：{selectedCourse.教师姓名}</Text>
            <Text>教室：{selectedCourse.教室 || '未安排'}</Text>
            <Title level={5}>课程评分</Title>
            <Text>水课程度：{selectedCourse.水课程度?.toFixed(1) || 'N/A'} / 10</Text>
            <Text>得分高低：{selectedCourse.得分高低?.toFixed(1) || 'N/A'} / 10</Text>
            <Text>评价数量：{selectedCourse.评价数量}</Text>
          </Space>
        )}
      </Modal>

      <Modal
        title="课程评价"
        visible={ratingModalVisible}
        onCancel={() => setRatingModalVisible(false)}
        footer={null}
      >
        <Form
          form={form}
          onFinish={values => {
            if (!selectedCourse) return;
            
            axios.post('http://localhost:5000/api/courses/ratings', {
              "课程编号": selectedCourse.原始课程编号,
              "教师编号": selectedCourse.教师编号,
              "得分高低（1到10）": values.得分高低,
              "水课程度（1到10）": values.水课程度
            })
              .then(response => {
                if (response.data.status === 'success') {
                  message.success('评价提交成功！');
                  setRatingModalVisible(false);
                  form.resetFields();
                } else {
                  message.error(response.data.message || '评价提交失败');
                }
              })
              .catch(error => {
                console.error('提交评价失败:', error);
                message.error('评价提交失败');
              });
          }}
        >
          <div style={{ marginBottom: 24 }}>
            <Text strong>评价课程：</Text>
            <Text>{selectedCourse?.课程名称}</Text>
          </div>
          <Form.Item
            name="得分高低"
            label="得分高低 (1-10分)"
            rules={[{ required: true, message: '请输入得分高低' }]}
          >
            <Input type="number" min="1" max="10" step="0.1" />
          </Form.Item>
          <Form.Item
            name="水课程度"
            label="水课程度 (1-10分)"
            rules={[{ required: true, message: '请输入水课程度' }]}
          >
            <Input type="number" min="1" max="10" step="0.1" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              提交评价
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Home; 